package com.example.newdemo.utils;

import android.content.Context;
import android.content.res.AssetManager;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class GetJsonFileDataUtil {

    /**
     *
     * @param fileName  assets 目录下的json文件
     * @return
     */
    public static String getJson(Context context , String fileName){
        StringBuilder stringBuilder = new StringBuilder();

        AssetManager assetManager = context.getAssets();

        InputStream inputStream = null;
        InputStreamReader inputReader = null ;
        try {

            inputStream = assetManager.open(fileName);
            inputReader = new InputStreamReader(inputStream);
            BufferedReader bf = new BufferedReader(inputReader);

            String line ;
            while ((line = bf.readLine()) != null){
                stringBuilder.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
                inputReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        return stringBuilder.toString();
    }


    public static <T> List<T> getObjectList(String jsonString, Class<T> cls){
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new Gson();
            JsonArray arry = new JsonParser().parse(jsonString).getAsJsonArray();
            for (JsonElement jsonElement : arry) {
                list.add(gson.fromJson(jsonElement, cls));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;

    }


}
